<template>
  <view class="inspection-task-container">
    <!-- 下拉刷新 -->
    <scroll-view 
      scroll-y="true" 
      refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      class="scroll-container"
    >

    <!-- 巡检任务列表 -->
    <view class="task-list">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 空数据提示 -->
      <view v-else-if="inspectionTasks.length === 0" class="empty-container">
        <text class="empty-text">暂无巡检任务</text>
      </view>
      
      <!-- 任务列表 -->
      <view v-else v-for="(item, index) in inspectionTasks" :key="index" class="task-card">
        <view class="task-content">
          <view class="info-row">
            <text class="info-label">任务名称：</text>
            <text class="info-value">{{ item?.planName || '' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">资产名称：</text>
            <text class="info-value">{{ item?.assetName || '' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">计划时间：</text>
            <text class="info-value">{{ item?.inspectionTime || '' }}</text>
            <view class="action-buttons">
              <text class="action-btn" @click="viewAssetDetail(item.id)">资产详情</text>
              <text class="action-btn" @click="startInspection(item)">巡检</text>
            </view>
          </view>
        </view>
             </view>
     </view>

     <!-- 分页器 -->
     <view class="pagination-container" v-if="total > 0">
       <uni-pagination 
         :total="total" 
         :pageSize="queryParams.pageSize" 
         :current="queryParams.pageNum"
         @change="onPageChange" 
         show-icon="true" 
       />
     </view>

     <!-- 资产巡检弹窗 -->
    <uni-popup ref="inspectionPopup" type="center" @close="closeInspection">
      <view class="inspection-popup">
        <view class="popup-header">
          <text class="popup-title">资产巡检</text>
          <text class="close-icon" @click="closeInspection">×</text>
        </view>
                 <view class="popup-content">
           <uni-forms ref="inspectionFormRef" :model="inspectionForm" :rules="rules">
             <!-- 巡检结果 -->
             <uni-forms-item label="巡检结果：" name="result">
               <uni-easyinput v-model="inspectionForm.result" placeholder="请输入"></uni-easyinput>
             </uni-forms-item>

             <!-- 巡检照片 -->
             <uni-forms-item label="巡检照片：" name="photos">
               <uni-file-picker 
                 v-model="inspectionForm.photos" 
                 limit="9" 
                 title="最多选择9张大小不超过 5MB 的图片" 
                 file-mediatype="image"   
                 @select="onPhotoSelect"
                 @delete="onPhotoDelete"
               ></uni-file-picker>
             </uni-forms-item>

             <!-- 备注 -->
             <uni-forms-item label="备注：" name="remarks">
               <uni-easyinput v-model="inspectionForm.remarks" type="textarea" placeholder="请输入"></uni-easyinput>
             </uni-forms-item>
           </uni-forms>
         </view>
        <view class="popup-footer">
          <button class="submit-btn" @click="submitInspection">提交巡检结果</button>
          <button class="cancel-btn" @click="closeInspection">取消</button>
        </view>
      </view>
    </uni-popup>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { listPlan, addRecord } from '@/api/user'
import useUserStore from '@/store/modules/user.js'
import { getToken } from '@/utils/auth'

// 基础URL
const baseUrl = import.meta.env.VITE_APP_BASE_URL

// 用户store
const userStore = useUserStore()

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 4,
  assetId: 0,
  createCompany: userStore.companyId
})

// 巡检任务数据
const inspectionTasks = ref([])
const total = ref(0)

// 加载状态
const loading = ref(false)
const refreshing = ref(false)

// 获取巡检任务列表
const getInspectionTasks = async () => {
  try {
    loading.value = true
    const response = await listPlan(queryParams.value)
    if (response && response.rows) {
      inspectionTasks.value = response.rows
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('获取巡检任务列表失败：', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 查看资产详情
const viewAssetDetail = (item) => {
  uni.navigateTo({
    url: `/pages/index/children/asset-details?assetId=${item}`,
  })
}

// 巡检弹窗相关
const inspectionPopup = ref(null)
const inspectionFormRef = ref(null)
const inspectionForm = ref({
  result: '',
  photos: [],
  remarks: ''
})

// 当前选中的巡检任务
const currentInspectionTask = ref(null)

// 巡检记录表单数据
const recordForm = ref({
  planId: null,
  assetId: null,
  executor: '',
  patrolTime: null,
  inspectionResults: null,
  picture: null,
  notes: ''
})

// 表单验证规则
const rules = {
  result: {
    rules: [{
      required: true,
      errorMessage: '请输入巡检结果'
    }]
  }
}

// 开始巡检
const startInspection = (item) => {
  // 保存当前选中的巡检任务
  currentInspectionTask.value = item
  
  // 初始化巡检记录表单数据
  recordForm.value = {
    planId: item.id,
    assetId: item.assetId,
    executor: userStore.name || '',
    patrolTime: new Date().toISOString().slice(0, 10), // 当前时间，格式：2025-07-05
    inspectionResults: null,
    picture: null,
    notes: ''
  }
  
  inspectionPopup.value.open()
}

// 关闭巡检弹窗
const closeInspection = () => {
  inspectionPopup.value.close()
  // 重置表单
  inspectionForm.value = {
    result: '',
    photos: [],
    remarks: ''
  }
  // 重置巡检记录表单
  recordForm.value = {
    planId: null,
    assetId: null,
    executor: '',
    patrolTime: null,
    inspectionResults: null,
    picture: null,
    notes: ''
  }
  // 清空当前选中的巡检任务
  currentInspectionTask.value = null
}

// 提交巡检结果
const submitInspection = async () => {
  try {
    await inspectionFormRef.value.validate()
    
    // 处理图片数据，将 uni-file-picker 格式转换为后端需要的格式
    let picture = ''
    if (inspectionForm.value.photos && inspectionForm.value.photos.length > 0) {
      const imageUrls = inspectionForm.value.photos.map((photo) => {
        // 从完整URL中提取相对路径
        if (photo.url && photo.url.startsWith(baseUrl)) {
          return photo.url.replace(baseUrl, '')
        }
        return photo.url
      })
      picture = imageUrls.join(',')
    }
    
    // 更新巡检记录表单数据
    recordForm.value.inspectionResults = inspectionForm.value.result
    recordForm.value.picture = picture
    recordForm.value.notes = inspectionForm.value.remarks
    
    console.log('提交巡检记录数据：', recordForm.value)
    
    // 调用 addRecord 接口提交巡检记录
    const response = await addRecord(recordForm.value)
    
    if (response.code === 200) {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
      closeInspection()
      // 刷新巡检任务列表
      getInspectionTasks()
    } else {
      uni.showToast({
        title: response.msg || '提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交巡检结果失败：', error)
    if (error.message === 'Token not found') {
      return // Token错误已经在uploadImage中处理
    }
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    })
  }
}

// 转换图片路径为 uni-file-picker 需要的格式
const convertImageToFilePickerFormat = (imagePath) => {
  const fileName = imagePath.split('/').pop() || 'image.jpg'
  const extname = fileName.split('.').pop() || 'jpg'
  const result = {
    name: fileName,
    extname: extname,
    url: baseUrl + imagePath,
  }
  console.log('转换图片格式:', imagePath, '->', result)
  return result
}

// 选择照片
const onPhotoSelect = async (e) => {
  console.log('选择照片', e)
  
  if (!e.tempFiles || e.tempFiles.length === 0) {
    uni.showToast({
      title: '请选择图片',
      icon: 'none'
    })
    return
  }

  // 检查文件大小（5MB = 5 * 1024 * 1024 bytes）
  const maxSize = 5 * 1024 * 1024
  
  for (let i = 0; i < e.tempFiles.length; i++) {
    const file = e.tempFiles[i]
    
    if (file.size > maxSize) {
      uni.showToast({
        title: `图片 ${file.name} 超过5MB限制`,
        icon: 'none'
      })
      return
    }
  }

  // 上传所有选中的图片
  for (let i = 0; i < e.tempFiles.length; i++) {
    const file = e.tempFiles[i]
    await uploadImage(file)
  }
}

// 上传单张图片
const uploadImage = (file) => {
  return new Promise((resolve, reject) => {
    // 检查token是否存在
    const token = getToken()
    if (!token) {
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      })
      reject(new Error('Token not found'))
      return
    }

    uni.showLoading({
      title: '上传中...'
    })

    uni.uploadFile({
      url: baseUrl + '/common/upload',
      filePath: file.path,
      name: 'file',
      header: {
        'Authorization': 'Bearer ' + getToken()
      },
      success: (uploadRes) => {
        uni.hideLoading()
        
        try {
          const result = JSON.parse(uploadRes.data)
          console.log('上传成功:', result)
          
          if (result.code === 200 && result.url) {
            // 将上传成功的图片添加到 inspectionForm.photos
            const imagePath = result.url.replace(baseUrl, '')
            const newPhoto = convertImageToFilePickerFormat(imagePath)
            inspectionForm.value.photos.push(newPhoto)
            
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: result.msg || '上传失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('解析上传响应失败:', error)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
        
        resolve()
      },
      fail: (error) => {
        uni.hideLoading()
        console.error('上传失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 删除照片
const onPhotoDelete = (e) => {
  console.log('删除照片', e)
  
  // e.index 是删除的图片索引
  if (e.index !== undefined && inspectionForm.value.photos[e.index]) {
    const deletedPhoto = inspectionForm.value.photos[e.index]
    console.log('删除的图片:', deletedPhoto)
    
    // 从 inspectionForm.photos 中移除该图片
    inspectionForm.value.photos.splice(e.index, 1)
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
  }
}

// 分页切换事件
const onPageChange = (e) => {
  queryParams.value.pageNum = e.current
  getInspectionTasks()
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  await getInspectionTasks()
  refreshing.value = false
}

// 页面加载时获取数据
onMounted(() => {
  getInspectionTasks()
})
</script>

<style>
.inspection-task-container {
  min-height: 100vh;
  background-color: #fff;
}

.scroll-container {
  height: 100vh;
}

.page-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #000;
  margin-right: 60rpx;
}

.task-list {
  padding: 20rpx;
}

.task-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.task-card:last-child {
  margin-bottom: 0;
}

.task-content {
  width: 100%;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  position: relative;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 28rpx;
  color: #666;
  flex: 1;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-left: 20rpx;
}

.action-btn {
  font-size: 28rpx;
  color: #007aff;
}

/* 巡检弹窗样式 */
.inspection-popup {
  background-color: #fff;
  border-radius: 16rpx;
  width: 90vw;
  max-height: 80vh;
  overflow: hidden;
}

.inspection-popup .popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.inspection-popup .popup-header .popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.inspection-popup .popup-header .close-icon {
  font-size: 40rpx;
  color: #666;
}

.inspection-popup .popup-content {
  padding: 30rpx;
}

/* uni-forms 样式调整 */
.inspection-popup .uni-forms-item {
  margin-bottom: 30rpx;
}

.inspection-popup .uni-forms-item:last-child {
  margin-bottom: 0;
}

.inspection-popup .uni-forms-item__label {
  font-size: 28rpx;
  color: #333;
}

.inspection-popup .uni-forms-item__content {
  margin-top: 10rpx;
}

.inspection-popup .popup-footer {
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.inspection-popup .submit-btn {
  width: 100%;
  height: 80rpx;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.inspection-popup .cancel-btn {
  width: 100%;
  height: 80rpx;
  background-color: #fff;
  color: #333;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 空数据样式 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 分页器样式 */
.pagination-container {
  background-color: #fff;
  padding: 30rpx;
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
}
</style>
